import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from  './store'
import './filter'// 加载过滤器
// var axios = require('axios')
// axios.defaults.baseURL = 'http://localhost:8080/api'
// // 全局注册，之后可在其他组件中通过 this.$axios 发送数据
// Vue.prototype.$axios = axios
// axios.defaults.withCredentials = true
import { http } from '@/services'; // 注意路径要和你的实际文件位置一致

// 将http挂载到Vue原型，命名为$axios（符合Vue全局属性命名规范）
Vue.prototype.$axios = http;

import ElementUI, {Message} from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.prototype.$message = Message;
Vue.config.productionTip = false
Vue.use(ElementUI)

import VueQuillEditor from 'vue-quill-editor'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

Vue.use(VueQuillEditor)

router.beforeEach((to, from, next) => {
    if (store.state.user.userName && to.path.startsWith('/admin')) {
      initAdminMenu(router, store)
    }
    // if(store.state.user.userName && this.$route.path === '/admin'){
    //   this.router.redirect('/admin/vote/list')
    // }
    // 已登录状态下访问 login 页面直接跳转到后台首页
    if (store.state.userName && to.path.startsWith('/login')) {
      next({
        path: 'admin/vote'
      })
    }
    if (to.meta.requireAuth) {
      if (store.state.user) {
        http.get('/authentication').then(resp => {
          if (resp) next()
        })
      } else {
        next({
          path: 'login',
          query: {redirect: to.fullPath}
        })
      }
    } else {
      next()
    }
  }
)

const initAdminMenu = (router, store) => {
  if (store.state.adminMenus.length > 0) {
    return;
  }
  http.get('/menu').then(resp => {
    if (resp && resp.status === 200) {
      var fmtRoutes = formatRoutes(resp.result)
      router.addRoutes(fmtRoutes)
      store.commit('initAdminMenu', fmtRoutes)
    }
  })
}

const formatRoutes = (routes) => {
  let fmtRoutes = []
  routes.forEach(route => {
    if (route.children) {
      route.children = formatRoutes(route.children)
    }

    let fmtRoute = {
      path: route.path,
      component: resolve => {
        require(['../components' + route.component + '.vue'], resolve)
      },
      name: route.name,
      nameZh: route.nameZh,
      iconCls: route.iconCls,
      meta: {
        requireAuth: true
      },
      children: route.children
    }
    fmtRoutes.push(fmtRoute)
  })
  return fmtRoutes
}


new Vue({
  router,
  render: h => h(App),
  store,
}).$mount('#app')

